package com.learn.sc.consul.comsumer.consulcomsumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import reactor.core.publisher.Mono;

@RestController
public class ServiceController {
	
	@Autowired
	private LoadBalancerClient loadBalancer;
	@Autowired
	private DiscoveryClient discoveryClient;
	@Autowired
	private FeignRemote feignRemote;
	
	@Value("${service.producer.id}")
	private String serviceProducerId;
	
	@RequestMapping("/services")
	public Mono<Object> services() {
		return Mono.just(discoveryClient.getInstances(serviceProducerId));
	}
	
	@RequestMapping("/discover")
	public Mono<Object> discover() {
		return Mono.just(loadBalancer.choose(serviceProducerId).getUri().toString());
	}
	
	@RequestMapping("/call")
	public Mono<String> callHello() {
		ServiceInstance serviceInstance = loadBalancer.choose(serviceProducerId);
		String url = serviceInstance.getUri().toString() + "/hello";
		String res = new RestTemplate().getForObject(url, String.class);
		return Mono.just(res);
	}
	
	@RequestMapping("/hello/{name}")
    public String index(@PathVariable("name") String name) {
        return feignRemote.hello(name);
    }
}
